package com.siyoumi.generator.controller;

import com.siyoumi.component.XApp;
import com.siyoumi.controller.BaseController;
import com.siyoumi.generator.entity.ColumnEntity;
import com.siyoumi.generator.entity.TableEntity;
import com.siyoumi.generator.mapper.MapperDb;
import com.siyoumi.generator.serivce.SysGeneratorSerivce;
import com.siyoumi.generator.util.XPage;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sys/generator")
public class SysGeneratorController
        extends BaseController {
    @Autowired
    private MapperDb mapperDb;
    @Autowired
    private SysGeneratorSerivce sysGeneratorSerivce;
    @Value("${server.port}")
    private int port;


    @RequestMapping()
    public String index() throws IOException {
        String txt = XApp.getFileContent("view/index.html");

        String apiRoot = XStr.format("http://127.0.0.1:{0}/", port + "");
        return txt.replace("{#api_root}", apiRoot);
    }

    /**
     * 列表
     */
    @RequestMapping("/table_list")
    public XReturn tableList(@RequestParam Map<String, Object> params) {
        XPage page = XPage.parse(params);
        List<TableEntity> list = mapperDb.tableList(page);
        List<TableEntity> newList = list.stream().map(entity ->
        {
            //类名称
            entity.setClassName(sysGeneratorSerivce.tableNameToClassName(entity.getTableName()));
            //包头
            Map<String, String> res = sysGeneratorSerivce.dbToPackageInfo(entity.getDb(), entity.getTableName());
            entity.setPackageEntity(res.get("package_entity"));

            return entity;
        }).collect(Collectors.toList());

        XReturn r = XReturn.getR(0);
        r.setData("list", newList);

        return r;
    }

    /**
     * 生成代码
     */
    @RequestMapping("/gen")
    public void gen(@RequestParam Map<String, String> params, HttpServletResponse response) throws IOException {
        String t = params.get("t");
        if (XStr.isNullOrEmpty(t)) {
            return;
        }

        String[] tableNames = t.split(",");

        ByteArrayOutputStream outputStream = sysGeneratorSerivce.gen(tableNames);
        byte[] data = outputStream.toByteArray();

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"entity.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }


    /**
     * 生成实体到项目
     */
    @RequestMapping("/genToJob")
    public XReturn genToJob(@RequestParam Map<String, String> params, HttpServletResponse response) throws IOException {
        String t = params.get("t");
        if (XStr.isNullOrEmpty(t)) {
            return XReturn.getR(20178, "miss t");
        }

        String[] tableNames = t.split(",");

        return sysGeneratorSerivce.genToJob(tableNames);
    }

    //http://127.0.0.1:8200/sys/generator/test
    @RequestMapping("/test")
    public XReturn test(@RequestParam Map<String, String> params, HttpServletResponse response) throws IOException {
        Map<String, Object> mapPage = new HashMap<>();
        mapPage.put("page_index", 0);
        mapPage.put("page_size", 300);
        List<TableEntity> listTable = mapperDb.tableList(mapPage);

        List<String> charArr = List.of("varchar", "char");
        List<String> colArr = new ArrayList<>();

        for (TableEntity table : listTable) {
            String tableName = table.getTableName();
            TableEntity tb = mapperDb.tableOne(tableName);

            //表字段
            List<ColumnEntity> cols = mapperDb.tableColumns(tableName);
            for (ColumnEntity col : cols) {
                if (!charArr.contains(col.getDataType())) {
                    continue;
                }
                //if ("utf8mb4_general_ci".equals(col.getCollationName())) {
                //    continue;
                //}

                String notNull = "DEFAULT NULL";
                if ("no".equals(col.getIsNullable().toLowerCase())) ;
                {
                    notNull = "NOT NULL";
                }
                notNull = "NOT NULL";

                String sql = XStr.format("ALTER TABLE `{0}`.`{1}` CHANGE COLUMN `{2}` `{2}` {3}({4}) {5};"
                        , tb.getDb()
                        , tb.getTableName()
                        , col.getColumnName()
                        , col.getDataType()
                        , col.getCharacterMaximumLength()
                        , notNull
                );

                colArr.add(sql);
            }
        }

        XReturn r = XReturn.getR(0);
        r.setData("col", colArr.stream().collect(Collectors.joining(" ")));

        return r;
    }
}
